<template>
  <div>
    <el-drawer
      custom-class="learn-drawer"
      title="课程管理"
      :visible.sync="drawer"
      direction="btt"
      size="100%"
      :modal="false"
      :before-close="drawerClose"
    >
      <!--      <el-container style="min-height: 100%">-->
      <div class="header">
        <div class="first" style="margin: 0 30px">
          <el-row class="content">
            <!--            $--color-primary-->
            <el-col :span="24" class="grid-content">
              <el-form>
                <el-form-item>
                  课程名称：{{typeForm.title}}
                </el-form-item>
              </el-form>
            </el-col>
            <el-col :span="8">
              <div>所属分类：{{typeForm.courseCate}}</div>
            </el-col>
            <el-col :span="8">
              <div>完成人数：{{typeForm.finishCount}}</div>
            </el-col>
            <el-col :span="8">
              <div>浏览人次：{{typeForm.viewCount}}</div>
            </el-col>
          </el-row>
          <el-row style="margin-top: 20px">
            <el-col :span="8">
              <div>学习人数：{{typeForm.userCount}}</div>
            </el-col>
            <el-col :span="8">
              <div>未完成人数：{{typeForm. unfinishCount}}</div>
            </el-col>
            <el-col :span="8">
              <div>未学习人数：{{typeForm.unStudyCount}}</div>
            </el-col>
          </el-row>
        </div>
        <div class="card" style="margin: 0 30px">
          <el-form style="display: flex;justify-content: space-between">
            <el-form-item>
              <span>课程学习列表</span>
            </el-form-item>
            <el-form-item>
            </el-form-item>
          </el-form>
          <el-form :model="dataForm" ref="dataForm" :rules="rules">
            <el-row :gutter="20" type="flex" align="bottom">
              <el-col :span="4">
                <el-form-item label="姓名:">
                  <el-input
                    v-model="dataForm.realname"
                    placeholder="请输入真实姓名"
                    clearable
                    style="width: 100%"
                  />
                </el-form-item>
              </el-col>
              <el-col :span="4">
                <el-form-item prop="deptId" label="部门" label-width="50px">
                  <el-cascader
                    placeholder="点击选择上级部门"
                    :options="deptList"
                    v-model="dataForm.deptId"
                    :props="deptListTreeProps"
                    filterable
                    clearable
                    change-on-select
                  />
                </el-form-item>
              </el-col>
              <el-col :span="4">
                <el-form-item label="职务:" prop="duty">
                  <el-select
                    v-model="dataForm.duty"
                    filterable
                    placeholder="请选择职务"
                    :loading="dutyLoading"
                    style="width: 100%"
                    clearable
                  >
                    <el-option
                      v-for="item in dutyList"
                      :key="item.id"
                      :label="item.label"
                      :value="item.description"
                    />
                  </el-select>
                </el-form-item>
              </el-col>
              <el-col :span="4">
                <el-form-item label="工种:" prop="craftName">
                  <el-select
                    filterable
                    v-model="dataForm.craftName"
                    placeholder="点击选择工种"
                    style="width: 100%"
                    filterable
                    clearable
                  >
                    <el-option
                      v-for="item in typeworkList"
                      :key="item.id"
                      :label="item.name"
                      :value="item.name"
                    />
                  </el-select>
                </el-form-item>
              </el-col>
              <el-col :span="5" v-if="activeName == 0">
                <el-form-item label="状态:" prop="courseStatus">
                  <el-radio-group v-model="dataForm.courseStatus" @change="search()" style="width: 100%">
                    <el-radio-button :label="1">全部</el-radio-button>
                    <el-radio-button :label="2">未学习</el-radio-button>
                    <el-radio-button :label="3">未完成</el-radio-button>
                    <el-radio-button :label="4">已完成</el-radio-button>
                  </el-radio-group>
                </el-form-item>
              </el-col>
              <el-col :span="5" v-if="activeName == 1">
                <el-form-item label="状态:" prop="courseExamStatus">
                  <el-radio-group v-model="dataForm.courseExamStatus" @change="search()">
                    <el-radio-button :label="3">全部</el-radio-button>
                    <el-radio-button :label="0">未参加</el-radio-button>
                    <el-radio-button :label="1">未通过</el-radio-button>
                    <el-radio-button :label="2">已通过</el-radio-button>
                  </el-radio-group>
                </el-form-item>
              </el-col>
              <el-col :span="4" style="display:flex;justify-content: flex-end">
                <el-form-item>
                  <el-button  type="primary" @click="_export()">导出</el-button>
                  <el-button type="primary" @click="search(1)" icon="el-icon-search">搜索</el-button>
                </el-form-item>
              </el-col>
            </el-row>
            <!--            <el-row>-->
            <!--              <el-col :span="3" v-if="dataForm.courseStatus == 2">-->
            <!--                <el-form-item label="时间:" prop="startTime">-->
            <!--                  <el-date-picker-->
            <!--                    v-model="dataForm.startTime"-->
            <!--                    type="daterange"-->
            <!--                    value-format="timestamp"-->
            <!--                    range-separator="至"-->
            <!--                    start-placeholder="开始日期"-->
            <!--                    end-placeholder="结束日期"-->
            <!--                  ></el-date-picker>-->
            <!--                </el-form-item>-->
            <!--              </el-col>-->
            <!--            </el-row>-->
          </el-form>
          <el-tabs v-model="activeName"  @tab-click="search(1)">
            <el-tab-pane label="学习管理" name="0">
              <!--              <Learning :data="data"></Learning>-->
              <div class="content">
                <el-table :data="data" border style="width: 100%;">
                  <el-table-column
                    type="index"
                    align="center"
                    header-align="center"
                    label="序号"
                    width="50px"
                  />
                  <el-table-column prop="realname" align="center" header-align="center" label="姓名"/>
                  <el-table-column
                    prop="deptName"
                    align="center"
                    header-align="center"
                    label="部门名称"
                  />
                  <el-table-column
                    prop="courseName"
                    align="center"
                    header-align="center"
                    label="课程名称"
                  />
                  <!--                  <el-table-column-->
                  <!--                    prop="startTime"-->
                  <!--                    align="center"-->
                  <!--                    header-align="center"-->
                  <!--                    label="开始时间"-->
                  <!--                  />-->
                  <!--                  <el-table-column-->
                  <!--                    prop="endTime"-->
                  <!--                    align="center"-->
                  <!--                    header-align="center"-->
                  <!--                    label="完成时间"-->
                  <!--                  />-->
                  <el-table-column
                    prop="courseStatus"
                    align="center"
                    header-align="center"
                    label="学习状态"
                  >
                    <template slot-scope="scope">
                      <span v-if="scope.row.courseStatus == 0">未学习</span>
                      <span v-if="scope.row.courseStatus == 1">未完成</span>
                      <span v-if="scope.row.courseStatus == 2">已完成</span>
                    </template>
                  </el-table-column>
                  <el-table-column label="操作" align="center" header-align="center">
                    <template slot-scope="scope">
                      <el-button
                        type="text"
                        @click="details(scope.row.userId)"
                      >详情
                      </el-button>
                    </template>
                  </el-table-column>
                </el-table>
                <el-pagination
                  @size-change="sizeChangeHandle"
                  @current-change="currentChangeHandle"
                  :current-page="pageIndex"
                  :page-sizes="[10, 20, 50]"
                  :page-size="pageSize"
                  :total="totalPage"
                  layout="total, sizes, prev, pager, next, jumper"
                ></el-pagination>
                <!--    详情-->
                <!--                <learn-deteil v-if="learnDetailVisible" ref="learnDeteil"></learn-deteil>-->
              </div>
            </el-tab-pane>
            <el-tab-pane label="考试管理" name="1" :loading="loading">
              <div class="content">
                <el-table :data="dataExam" border style="width: 100%;" v-loading="loading">
                  <el-table-column
                    type="index"
                    align="center"
                    header-align="center"
                    label="序号"
                    width="50px"
                  />
                  <el-table-column prop="realname" align="center" header-align="center" label="姓名"/>
                  <el-table-column
                    prop="deptName"
                    align="center"
                    header-align="center"
                    label="部门名称"
                  />
                  <el-table-column
                    prop="courseName"
                    align="center"
                    header-align="center"
                    label="课程名称"
                  />
                  <el-table-column
                    prop="courseExamStatus"
                    align="center"
                    header-align="center"
                    label="考试状态"
                  >
                    <template slot-scope="scope">
                      <span v-if="scope.row.courseExamStatus == 0">未参加</span>
                      <span v-if="scope.row.courseExamStatus == 1">未通过</span>
                      <span v-if="scope.row.courseExamStatus == 2">已通过</span>
                    </template>
                  </el-table-column>
                  <el-table-column label="操作" align="center" header-align="center">
                    <template slot-scope="scope">
                      <el-button type="text" @click="detail(scope.row.userId)">详情</el-button>
                    </template>
                  </el-table-column>
                </el-table>
                <el-pagination
                  @size-change="sizeChangeHandles"
                  @current-change="currentChangeHandles"
                  :current-page="page"
                  :page-sizes="[10, 20, 50]"
                  :page-size="limit"
                  :total="total"
                  layout="total, sizes, prev, pager, next, jumper"
                ></el-pagination>
                <!--    详情-->
              </div>
              <!--              <learn-Exam :dataExam="dataExam"></learn-Exam>-->
            </el-tab-pane>
          </el-tabs>
        </div>
      </div>
      <el-main style="height:100px;overflow: auto"></el-main>
    </el-drawer>
    <learn-deteil v-if="learnDetailVisible" ref="learnDeteil"></learn-deteil>
    <learn-exam-deteil v-if="learnExamDetailVisible" ref="learnexamDeteil"></learn-exam-deteil>
  </div>
</template>

<script>
  // import Learning from './learning'
  // import LearnExam from './learn-exam'
  import learnDeteil from './learning-detail'
  import learnExamDeteil from './learn-exam-detail'
  import SearchForm from '../../../components/search-form/search-form'
  import LearnAdduser from './learn-add-user'
  import {treeDataTranslate} from '@/utils'
  // import {treeDataTranslate} from '@/utils'

  export default {
    name: 'adminilstration',
    data () {
      return {
        learnExamDetailVisible: false,
        learnDetailVisible: false,
        dutyLoading: false,
        loading: true,
        addOrUpdateVisible: false,
        dialogFormVisible: false,
        courseId: '',
        userIds: [],
        data: [],
        dataExam: [],
        typeForm: {},
        activeName: '0',
        dataForm: {
          type: 'DUTY',
          realname: '',
          duty: '',
          identityCard: '',
          deptId: '',
          userIds: [],
          craftId: '',
          craftName: '',
          courseStatus: 1,
          statusType: '',
          startTime: '',
          endTime: '',
          relateType: '',
          courseExamStatus: 3
        },
        deptListTreeProps: {
          checkStrictly: true,
          expandTrigger: 'click',
          label: 'name',
          value: 'id',
          children: 'children',
          emitPath: false
        },
        pageIndex: 1,
        pageSize: 10,
        page: 1,
        limit: 10,
        totalPage: 0,
        total: 0,
        dutyList: [],
        deptList: [],
        typeworkList: [],
        deptName: '',
        userList: [],
        drawer: false,
        rules: {
          // courseStatus: [
          //   {required: true, message: '学习类型不能为空', trigger: 'blur'}
          // ]
        }
      }
    },
    components: {SearchForm, LearnAdduser, learnDeteil, learnExamDeteil},
    methods: {
      drawerClose () {
        this.step = 0
        this.drawer = false
      },
      // 学习管理详情
      details (id) {
        this.learnDetailVisible = true
        this.$nextTick(() => {
          this.$refs.learnDeteil.init(id, this.courseId)
        })
      },
      // 考试管理详情
      detail (id) {
        this.learnExamDetailVisible = true
        this.$nextTick(() => {
          this.$refs.learnexamDeteil.init(id, this.courseId)
        })
      },
      init (id) {
        this.courseId = id
        this.dataForm = {
          type: 'DUTY',
          realname: '',
          duty: '',
          identityCard: '',
          deptId: '',
          userIds: [],
          craftId: '',
          craftName: '',
          courseStatus: 1,
          statusType: '',
          // relateType: '',
          courseExamStatus: 3
        }
        this.getshowcoursenumbers()
        this.activeName = '0'
        this.pageIndex = 1
        this.pageSize = 10
        this.page = 1
        this.limit = 10
        this.getTypeworkList()
        this.getDutyList()
        this.getDeptList()
        this.search()
        this.$nextTick(() => {
          this.$refs['dataForm'].resetFields()
        })
        // this.getUsercenterList()
        this.drawer = true
        // this.$nextTick(_ => this.$refs.searchForm.init())
      },
      getshowcoursenumbers () {
        this.$http({
          url: this.$http.adornUrl(
            `/train-admin/courseManage/showCourseNumbers`
          ),
          method: 'post',
          data: {
            courseId: this.courseId
          }
        }).then(data => {
          // this.dataForm = Object.assign(this.dataForm, data.data)
          this.typeForm = data.data
        })
      },
      // 每页数
      sizeChangeHandle (val) {
        this.pageSize = val
        this.pageIndex = 1
        this.search()
      },
      // 当前页
      currentChangeHandle (val) {
        console.log(val)
        this.pageIndex = val
        this.search()
      },
      sizeChangeHandles (val) {
        this.limit = val
        this.page = 1
        this.search()
      },
      // 当前页
      currentChangeHandles (val) {
        this.page = val
        this.search()
      },
      search (val) {
        console.log(val)
        this.loading = true
        let arr = [
          'realname',
          'duty',
          'identityCard',
          'deptId',
          'craftId',
          'craftName',
          'statusType'
        ].map(x => this.dataForm[x])
        let search = Object.values(arr).filter(x => x !== '' && x !== null)
        if (search.length) {
          this.$http({
            url: this.$http.adornUrl('/usercenter-admin/user/getListByQueryInfo'),
            method: 'post',
            data: {
              realname: this.dataForm.realname,
              duty: this.dataForm.duty,
              craftName: this.dataForm.craftName,
              identityCard: this.dataForm.identityCard,
              deptId: this.dataForm.deptId
            }
          }).then(data => {
            this.userList = data.data
            if (this.userList.length) {
              // this.getUsercenterList()
              // eslint-disable-next-line no-unused-vars
              // let userIds = []
              let userIds = data.data.map(x => x.userId).join(',')
              this.getUsercenterList(userIds, val)
            } else {
              this.data = []
              this.totalPage = 0
              this.total = 0
              this.userList = []
              this.userIds = []
              this.dataExam = []
            }
          })
        } else {
          this.userIds = []
          this.getUsercenterList()
        }
      },
      getUsercenterList (userIds, page) {
        console.log(page)
        if (page) this.pageIndex = page
        this.dataExam = []
        this.data = []
        this.userIds = this.userList.map(x => x.userId).join(',')
        // eslint-disable-next-line eqeqeq
        if (this.activeName == 0) {
          this.$http({
            url: this.$http.adornUrl('/train-admin/sta/user'),
            method: 'post',
            data: {
              searchUserIds: userIds,
              courseId: this.courseId,
              courseStatus: this.dataForm.courseStatus,
              // startTime: this.dataForm.startTime,
              // endTime: this.dataForm.endTime,
              page: this.pageIndex,
              limit: this.pageSize
            }
          }).then(data => {
            if (data.code === 200) {
              this.loading = false
              this.data = data.data.list
              this.totalPage = data.data.totalCount
              this.userList = []
              this.userIds = []
            } else {
              this.loading = false
              this.userList = []
              this.userIds = []
              this.$notify.error({
                title: '失败',
                message: data.msg
              })
            }
          })
        } else {
          if (page) this.page = page
          this.$http({
            url: this.$http.adornUrl(
              '/train-admin/coursemanage/usercourseexamlist'
            ),
            method: 'post',
            data: {
              userIds: userIds,
              courseId: this.courseId,
              courseExamStatus: this.dataForm.courseExamStatus,
              startTime: this.dataForm.startTime,
              endTime: this.dataForm.endTime,
              page: this.page,
              limit: this.limit
            }
          }).then(data => {
            if (data.code === 200) {
              this.loading = false
              this.dataExam = data.data.list
              this.total = data.data.totalCount
              this.userList = []
              this.userIds = []
            } else {
              this.loading = false
              this.userList = []
              this.userIds = []
              // this.$notify.error({
              //   title: '失败',
              //   message: data.msg
              // })
            }
          })
        }
      },
      addLearner () {
        this.addOrUpdateVisible = true
        this.$nextTick(() => {
          this.$refs.learnadduser.init(this.courseId)
        })
      },
      // 获取职务列表
      async getDutyList () {
        this.dutyLoading = true
        this.$http({
          url: this.$http.adornUrl('/usercenter-admin/dict/type'),
          method: 'post',
          data: {type: this.dataForm.type}
        }).then(data => {
          this.dutyLoading = false
          this.dutyList = data.data
        })
      },
      // 获取部门列表
      async getDeptList () {
        this.$http({
          url: this.$http.adornUrl('/usercenter-admin/dept/list'),
          method: 'post'
        }).then(res => {
          console.log(res)
          // this.deptList = res.data
          this.deptList = treeDataTranslate(
            res.data.filter(item => item.parentId !== -1),
            'id'
          )
          // this.deptList = this.deptList.splice(0, 1)
          // this.deptList = treeDataTranslate(res.data.filter(item => item.parentId !== -1), 'id')
        })
      },
      // 获取工种列表
      async getTypeworkList () {
        this.$http({
          url: this.$http.adornUrl(`/usercenter-admin/user/craft/list`),
          method: 'post'
        }).then(res => {
          this.typeworkList = res.data
        })
      },
      // 菜单树选中
      deptListTreeCurrentChangeHandle (data, node) {
        this.deptName = data.name
        this.dataForm.deptId = data.id
      },
      // 菜单树设置当前选中节点
      deptListTreeSetCurrentNode () {
        this.$refs.deptListTree.setCurrentKey(this.dataForm.deptId)
        this.dataForm.deptName = (this.$refs.deptListTree.getCurrentNode() || {})['name']
      },
      _export() {
        window.location = this.$http.downloadUrl(
          '/train-admin/courseManage/userCourseListExport',
          {
            courseId: this.courseId,
            courseStatus: this.dataForm.courseStatus
          }
        )
      },
      // 总导出状态
      downloadUserAndCert () {
        // eslint-disable-next-line one-var
        let coursewareCount = 0, examCount = 0
        this.$http({
          url: this.$http.adornUrl(
            `/train-admin/coursemanage/usercourselistexport`
          ),
          method: 'post',
          data: {
            page: this.pageIndex,
            limit: 99999,
            courseStatus: 4,
            courseId: this.courseId
          }
        }).then(res => {
          // eslint-disable-next-line no-undef,eqeqeq
          let dataList = res && res.code == 200 ? res.data.courseList : []
          coursewareCount = res.data.coursewareCount
          examCount = res.data.examCount
          dataList.forEach(x => {
            x.coursewareStatus = x.coursewareStatus === 0 ? '未学习' : x.coursewareStatus === 1 ? '未完成' : '已完成'
            x.courseStatus = x.courseStatus === 0 ? '未学习' : x.courseStatus === 1 ? '未完成' : '已完成'
            x.courseExamStatus = x.courseExamStatus === 0 ? '未参加' : x.courseExamStatus === 1 ? '未通过' : '已通过'
          })
          import('@/vendor/Export2Excel').then(excel => {
            let tHeader = [
              '姓名',
              '部门',
              '课程名称'
            ]
            if (coursewareCount > 0) tHeader.push('学习状态')
            if (examCount > 0) tHeader.push('考试状态')
            tHeader.push('总状态')
            const filterVal = [
              'realname',
              'deptName',
              'courseName'
            ]

            if (coursewareCount > 0) filterVal.push('courseStatus')
            if (examCount > 0) filterVal.push('courseExamStatus')
            filterVal.push('courseStatus')
            const data = this.formatJson(filterVal, dataList)
            excel.export_json_to_excel({
              header: tHeader,
              data,
              // filename: `"${res.data.list[0].examName}"安全考试成绩汇总表${new Date().toLocaleDateString()}`
              filename: '学习管理'
            })
          })
        })
      },
      formatJson: (filterVal, jsonData) =>
        jsonData.map(v => filterVal.map(j => v[j]))
    }
  }
</script>
<style lang="scss">
  .header {
    width: 100%;
  }
  .first {
    height: 140px;
    /*background: #F8F8FF;*/
    border: 1px solid #6c7a86;
    margin: 10px;
  }

</style>
